;
import LocalStorageManager from "./LocalStorageManager";
import Singleton from "./SingleTon";

/**
 * 音效管理
 */

export default class SoundManager extends Singleton {
    /**背景音乐开关 */
    private _musicOnOf: boolean = true;
    /**音效开关 */
    private _effectOnOf: boolean = true;

    /**背景声音大小默认值 */
    private _musicVolume: number = 0.6;

    /**音效大小默认值 */
    private _audioVolume: number = 0.6;

    private _musicAudioId: number = -1;

    public init() {
        this.loadLocalCfg();
    }

    private loadLocalCfg() {
        // 读取本地音效开关配置
        let soundCfg = LocalStorageManager.getItem("soundCfg");
        if (soundCfg) {
            this._musicOnOf = soundCfg.musicOnOf;
            this._effectOnOf = soundCfg.effectOnOf;
            this._musicVolume = soundCfg.musicVolume;
            this._audioVolume = soundCfg.audioVolume;
        } else {
            this.updateStorage();
        }
        
        cc.audioEngine.setMusicVolume(this._musicVolume);
        cc.audioEngine.setEffectsVolume(this._audioVolume);
    }

    private updateStorage() {
        let soundCfg = {
            musicOnOf: this._musicOnOf,
            effectOnOf: this._effectOnOf,
            musicVolume: this._musicVolume,
            audioVolume: this._audioVolume
        }

        LocalStorageManager.setItem("soundCfg", soundCfg);
    }

    public stopMusic() {
        cc.audioEngine.stop(this._musicAudioId);
    }

    public setMusicVolume(volume: number) {
        this._musicVolume = volume;
        this.updateStorage();
        cc.audioEngine.setMusicVolume(volume);
    }

    public setAudioVolume(volume: number) {
        this._audioVolume = volume;
        this.updateStorage();
        cc.audioEngine.setEffectsVolume(volume);
    }

    public getMusicVolume(): number {
        let soundCfg = LocalStorageManager.getItem("soundCfg");
        return soundCfg.musicVolume;
    }

    public getAudioVolume(): number {
        let soundCfg = LocalStorageManager.getItem("soundCfg");
        return soundCfg.audioVolume;
    }
}
